<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表单验证</title>
    <style>
        .error { color: red; }
    </style>
</head>
<body>
    <h1>用户注册</h1>
    <form id="registrationForm">
        <label for="username">用户名:</label>
        <input type="text" id="username" name="username">
        <span id="usernameError" class="error"></span><br><br>

        <label for="email">邮箱:</label>
        <input type="text" id="email" name="email">
        <span id="emailError" class="error"></span><br><br>

        <label for="password">密码:</label>
        <input type="password" id="password" name="password">
        <span id="passwordError" class="error"></span><br><br>

        <button type="submit">注册</button>
    </form>

    <script>
        document.getElementById('registrationForm').addEventListener('submit', function(event) {
            event.preventDefault();

            let username = document.getElementById('username').value;
            let email = document.getElementById('email').value;
            let password = document.getElementById('password').value;
            let isValid = true;

            if (username.length < 3) {
                document.getElementById('usernameError').textContent = '用户名必须至少3个字符!';
                isValid = false;
            } else {
                document.getElementById('usernameError').textContent = '';
            }

            if (!/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/.test(email)) {
                document.getElementById('emailError').textContent = '请输入有效的邮箱!';
                isValid = false;
            } else {
                document.getElementById('emailError').textContent = '';
            }

            if (password.length < 6) {
                document.getElementById('passwordError').textContent = '密码必须至少6个字符!';
                isValid = false;
            } else {
                document.getElementById('passwordError').textContent = '';
            }

            if (isValid) {
                alert('注册成功!');
            }
        });
    </script>
</body>
</html>
